package com.hyh.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.util.Log;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created by zzkong on 2017/5/31.
 */
public class AppManager {

    public static final int STATUS_FORCE_KILLED = -1; //应用放在后台被强杀了
    public static final int STATUS_NORMAL = 1; //APP正常态
    public int appStatus = STATUS_FORCE_KILLED; //APP状态 初始值为没启动 不在前台状态

    public static Stack<Activity> activityStack;
    private static AppManager instance;

    private static final String TAG = "AppManager";

    private AppManager() {
    }

    public static void release() {
        instance = null;
    }

    /**
     * 单一实例
     * (添加线程安全锁)
     */
    public static AppManager getAppManager() {
        if (instance == null) {
            synchronized (AppManager.class) {
                if (instance == null) {
                    instance = new AppManager();
                }
            }
        }
        return instance;
    }

    /**
     * 添加Activity到堆栈
     */
    public void addActivity(Activity activity) {
    //    Log.d(TAG,"------addActivity--activityStack="+activityStack);
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        Log.d(TAG,"------addActivity="+activity);
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    public Activity currentActivity() {
        Activity activity = activityStack != null ? activityStack.lastElement() : null;
        return activity;
    }

    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = activityStack != null ? activityStack.lastElement() : null;
        finishActivity(activity);
    }

    /**
     * 结束指定的Activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            if (activityStack != null) {
                activityStack.remove(activity);
                Log.d(TAG,"------activityStack.remove="+activity);
            }
//          activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public void finishActivity(Class<?> cls) {
        if (activityStack == null) {
            return;
        }
        for (Activity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
                activity.finish();
                Log.i("flh_log", "finishActivity: " + cls);
            }
        }
    }

    /**
     * 结束除指定activity外的所有activity
     */
    public void finishOtherActivity(Class<?> act){
        if (activityStack == null)return;
        List<Activity> list = new ArrayList<>();
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {

                String clsName = activityStack.get(i).getClass().getName();
                Log.e("androidLog","clsName="+clsName);
                if(!(clsName.contains("GuideActivity")
                        || clsName.contains("com.ctyon.watch.ui.main.MainActivity")
                        || clsName.contains("com.ctyon.watch.echocloud.view.VoiceActivity")
                        || clsName.contains("LockScreenActivity")
                        || clsName.contains("unAcceptCallActivity")
                        || clsName.contains("NewMessageTipActivity")
                        || clsName.contains("ForbidUseActivity")
                        || clsName.contains("ClockAlarmActivity")
                        || clsName.contains(act.getName()))){
                    dbg.d("kill activity "+clsName);
                    list.add(activityStack.get(i));
                }
            }
        }
        for(Activity activity:list){
            activityStack.remove(activity);
            activity.finish();
        }
        Log.d(TAG,"------activityStack="+activityStack);
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        if (activityStack == null) {
            return;
        }

        List<Activity> list = new ArrayList<>();
        for (int i = 0, size = activityStack.size(); i < size; i++) {
            if (null != activityStack.get(i)) {

                String clsName = activityStack.get(i).getClass().getName();
                Log.e("androidLog","clsName="+clsName);
                if(!(clsName.contains("GuideActivity")
                        || clsName.contains("com.ctyon.watch.ui.main.MainActivity")
                        || clsName.contains("com.ctyon.watch.echocloud.view.VoiceActivity")
                        || clsName.contains("LockScreenActivity")
                        || clsName.contains("unAcceptCallActivity")
                        || clsName.contains("NewMessageTipActivity")
                        || clsName.contains("ForbidUseActivity")
                        || clsName.contains("ClockAlarmActivity")
                        || clsName.contains("G51LowBatteryActivity"))){
                    dbg.d("kill activity "+clsName);
                    list.add(activityStack.get(i));
                }
            }
        }

        for(Activity activity:list){
            activityStack.remove(activity);
            activity.finish();
        }
    //    activityStack.clear();
        Log.d(TAG,"------activityStack="+activityStack);
    }

    /**
     * 退出应用程序
     */
    public void AppExit(Context context) {
        try {
            finishAllActivity();
            ActivityManager activityMgr =
                    (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            activityMgr.killBackgroundProcesses(context.getPackageName());
            System.exit(0);
        } catch (Exception e) {
        }
    }

    public boolean isAppExit() {
        return activityStack == null || activityStack.isEmpty();
    }

    public int getAppStatus() {
        return appStatus;
    }

    public void setAppStatus(int appStatus) {
        this.appStatus = appStatus;
    }

    public static String getAppVersionName(Context context) {
        PackageManager manager = context.getPackageManager();
        String version = null;
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            version = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version;
    }

    public static boolean checkApplication(Context context, String packageName){
        if(TextUtils.isEmpty(packageName)){
            return false;
        }
        try {
            context.getPackageManager().getApplicationInfo(packageName,PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void forceStopPackage(Context context, String packageName){
        try {
            ActivityManager mActivityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
            Method forceStopPackageMethod = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String.class);
            forceStopPackageMethod.setAccessible(true);
            forceStopPackageMethod.invoke(mActivityManager, packageName);
        } catch (Exception e) {
        }
    }

    public boolean isApplicationRunning(Context context,String packagename) {
        ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> mRunningProcess = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo amProcess : mRunningProcess){
            if(amProcess.processName.equals(packagename)){
                return true;
            }
        }
        return false;
    }

    public static boolean checkActivity(Context context,String packgeName,String className){
        Intent intent = new Intent();
        intent.setClassName(packgeName, className);
        if (context.getPackageManager().resolveActivity(intent, 0) == null) {
            return false;
        }else{
            return true;
        }
    }

    public static boolean checkActivity(Context context,Intent intent){
        if (context.getPackageManager().resolveActivity(intent, 0) == null) {
            return false;
        }else{
            return true;
        }
    }

    public  Activity getActivity(String activityName){
        Log.d(TAG,"-getActivity-----activityStack="+activityStack);
        for(Activity activity:activityStack){
        //    Log.d(TAG,"-getActivity-----activity="+activity.getComponentName().getClassName());
            if(activity.getComponentName().getClassName().contains(activityName)){
                return activity;
            }
        }
        return null;
    }

    public static boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param activity 要判断的Activity
     * @return 是否在前台显示
     */
    public static boolean isForeground(Activity activity) {
        return isForeground(activity, activity.getClass().getName());
    }

    /**
     * 判断某个界面是否在前台
     *
     * @param context   Context
     * @param className 界面的类名
     * @return 是否在前台显示
     */
    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (cpn.getClassName().contains(className))
                return true;
        }
        return false;
    }
}